package me.itblog.mvc.modules.admin;

import me.itblog.bean.User;
import me.itblog.mvc.modules.BaseModule;
import me.itblog.services.UserService;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.Scope;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;

/**
 * Created by infi.he on 2015/12/1.
 */
@IocBean()
@At("/admin")
public class AdminModule extends BaseModule {
    private Logger logger = LoggerFactory.getLogger(AdminModule.class);

    @Inject
    Dao dao;

    @Inject
    UserService userService;

    @At("/ajaxLogin")
    public Object ajaxLogin(@Param("username") String username, @Param("password") String password) {
        NutMap reslult = null;
        User fetch = userService.fetch(username, password);
        if (fetch != null) {
            HttpSession httpSession = Mvcs.getHttpSession();
            httpSession.setAttribute("me", fetch);
            reslult = ajaxOk("");
        } else {
            reslult = ajaxFail("账号或者密码不正确");
        }
        return reslult;
    }

    @At("/changepwd")
    public Object changepwd(@Param("oldPwd") String oldPwd,
                            @Param("newPwd") String newPwd, @Attr(scope = Scope.SESSION, value = "me") User me) {
        NutMap reslult = null;
        int r =  userService.changepwd(me,oldPwd, newPwd);
        if(r == 0){
            reslult = ajaxFail("密码不正确");
        } else {
            reslult = ajaxOk("");
        }
        return reslult;
    }
}
